<style scoped>
.webSocket {
  width: 100%;
  height: 100vh;
  /* background: red; */
}

.webSocket_title {
  width: 100%;
  height: 10vh;
  /* background: green; */
  font-size: 5vh;
  text-align: center;
  font-weight: bold;
  line-height: 10vh;
  color: #303133;
}

.webSocket_content {
  width: 100%;
  height: 89vh;
  border-top: 1vh solid #ebeef5;
  /* background: salmon; */
}

.webSocket_notice {
  width: 69%;
  height: 89vh;
  float: left;
  /* background: darkblue; */
  border-right: 1vh solid #ebeef5;
}

.webSocket_notice_title {
  width: 100%;
  height: 5vh;
  /* background: darkgreen; */
  text-align: center;
  font-size: 2.5vh;
  line-height: 5vh;
  color: #409eff;
  font-weight: bold;
}

.webSocket_notice_announcement {
  width: 100%;
  height: 84vh;
  /* background: salmon; */
  overflow: auto;
}

.webSocket_notice_announcement_item {
  width: 99%;
  margin: 0 auto;
  height: auto;
  border: 1px solid #e4e7ed;
  border-radius: 5px;
  margin-top: 1vh;
  font-size: 0.6vw;
  font-weight: bold;
}

.webSocket_chat {
  width: 30%;
  height: 89vh;
  float: right;
  /* background: darkcyan; */
}

.webSocket_chat_top {
  width: 100%;
  height: 40vh;
  /* background: red; */
}

.webSocket_chat_top_input {
  width: 100%;
  height: 4vh;
  /* background: green; */
}

.webSocket_chat_top_textarea {
  width: 100%;
  height: 35vh;
  /* background: darkseagreen; */
}

.webSocket_chat_bottom {
  width: 100%;
  height: 49vh;
  /* background: sandybrown; */
  overflow: auto;
}
.webSocket_chat_bottom_item {
  width: 99%;
  margin: 0 auto;
  height: auto;
  border-bottom: 1px solid #e4e7ed;
  margin-top: 1vh;
  font-size: 0.6vw;
  font-weight: bold;
}
</style>
<template>
  <div class="webSocket">
    <div class="webSocket_title">
     test websocket
    </div>
    <div class="webSocket_content">
      <div class="webSocket_notice">
        <div class="webSocket_notice_title">
          系统信息监控Notice
        </div>
        <div class="webSocket_notice_announcement">
          <div
            class="webSocket_notice_announcement_item"
            v-for="(item, index) in arrys"
            :key="index"
          >
            系统名称：{{ item.OsName }} --- cpu负载：{{ item.CpuLoad }} ---
            jvm线程负载：{{ item.ProcessCpuLoad }} --- 物理总内存：{{
              item.TotalMemorySize
            }}
            --- 已使用的物理内存：{{ item.UsedMemory }} --- 剩余物理内存：{{
              item.FreePhysicalMemorySize
            }}
            --- 时间：{{ item.Time }}
          </div>
        </div>
      </div>
      <div class="webSocket_chat">
        <p>点对点通信</p>
        <div class="webSocket_chat_top">
          <div class="webSocket_chat_top_input">
            发送方<input type="text" v-model="fromName" placeholder="发送方姓名" /><br>
            接收方<input type="text" v-model="toName" placeholder="接收方姓名" /><br>
            <button :disabled="oneD" @click="onChatConnect">连接</button>
            <button :disabled="twoD" @click="onDisconConnect">断开连接</button>
          </div>
          <br><br><br>
          <div v-show="textareaS" class="webSocket_chat_top_textarea">
            <textarea rows="5" cols="30" v-model="message" />
            <button @click="onSendMessage">发送消息</button>
          </div>
        </div>
        <br><br>
        <br><br><br>
        <div class="webSocket_chat_bottom">
          <div
            class="webSocket_chat_bottom_item"
            v-for="(item, index) in chatArray"
            :key="index"
          >
            发送方：{{ item.fromName }} 内容： {{ item.content }} 时间：{{
              item.time
            }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import SockJS from "sockjs-client";
import Stomp from "stompjs";
export default {
  name: "WebSocketTest",
  data() {
    return {
      arrys: [],
      chatArray: [],
      stompClient: "",
      timer: "",
      fromName: "",
      toName: "",
      message: "",
      oneD: false,
      twoD: true,
      textareaS: false
    };
  },
  created() {},
  mounted() {
    this.initWebSocket();
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.disconnect();
  },
  methods: {
    initWebSocket() {
      this.connection();
      let that = this;
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          if (that.stompClient !== undefined ||  that.stompClient !== ""){
            that.stompClient.send("/app/test");
          }
        } catch (err) {
          console.log("断线了: " + err);
          that.connection();
        }
      }, 5000);
    },

    /**
     * 连接后台ws
     */
    connection() {
      var _this = this;
      // 建立连接对象
      let socket = new SockJS("/ws");
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(socket);
      // 定义客户端的认证信息,按需求配置
      let headers = {
        Authorization: ""
      };
      // 向服务器发起websocket连接
      this.stompClient.connect(
        headers,
        function(res) {
          //连接成功 订阅系统信息主题消息
          _this.stompClient.subscribe("/topic/SystemInfo", function(msg) {
            _this.arrys.unshift(JSON.parse(msg.body));
          });
        },
        function(error) {
          // 连接发生错误时的处理函数
          console.log("失败");
          console.log(error);
        }
      );
    },

    /**
     * 断开连接
     *
     */
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
    },
    /**
     * chat 连接
     */
    onChatConnect() {
      var _this = this;
      if (this.fromName == "" || this.toName == "") {
        alert("发送或接收方姓名不能为空");
        return;
      }
      console.log(this.stompClient)
      if (this.stompClient !== undefined && this.stompClient !== null && this.stompClient !== "") {
        _this.oneD = true;
        _this.twoD = false;
        _this.textareaS = true;
        this.stompClient.subscribe("/chat/" + _this.fromName, function(msg) {
          console.log(msg)
          console.log(_this.chatArray)
          _this.chatArray.unshift(JSON.parse(msg.body));
        });
      } else {
        let socket = new SockJS("/ws");
        this.stompClient = Stomp.over(socket);
        let headers = {
          Authorization: ""
        };
        // 向服务器发起websocket连接
        this.stompClient.connect(
          headers,
          function(res) {
            _this.oneD = true;
            _this.twoD = false;
            _this.textareaS = true;
            _this.stompClient.subscribe("/chat/" + _this.toName, function(msg) {
              console.log(this.stompClient)
              console.log(msg)
              console.log(_this.chatArray)
              _this.chatArray.unshift(JSON.parse(msg.body));
            });
          },
          function(error) {
            console.log("失败");
            console.log(error);
          }
        );
      }
    },

    /**
     * chat 伪断开连接
     */
    onDisconConnect() {
      this.fromName = "";
      this.toName = "";
      this.oneD = false;
      this.twoD = true;
      this.textareaS = false;
    },

    /**
     * 发送消息
     */
    onSendMessage() {
      var obj = {
        fromName: this.fromName,
        toName: this.toName,
        content: this.message
      };
      this.stompClient.send("/app/chat/message", {}, JSON.stringify(obj));
      this.message = "";
    }
  }
};
</script>
